<?php
/**
 * 中益检测仪接口控制器 继承A控制器，A控制器的控制接口秘钥登录
 */
namespace Api\Controller;
use Think\Controller;
class ZyApiController extends AController {
    public function _empty(){
        echo '中益检测仪接口访问地址错误';
    }
    //1.用户登录接口
    public function zy_login(){
        $name = I('login_name');
        $pass = I('password');
        $parame = array(
            'login_name'=>$name,
            'password'=>$pass
        );
        AddLog($parame,'用户登录');
        if(!$name || !$pass){
            $arr = array(
                'code'=>0,
                'msg'=>'参数错误(Parameter error)'
            );
            $this->ajaxReturn($arr);
        }
        //查询用户名是否存在
        $w['name']=$name;
        $w['email']=$name;
        $w['phone']=$name;
        $w['_logic']='OR';
        $w_1['password']=$pass;
        $w_1['_complex']=$w;
        $res = M('user')->where($w_1)->find();
        if($res){
            //用户登录成功，在检测表中写入用户检测状态
            $d = array(
                'uid'=>$res['id'],
                'equipment_id'=>$equipment_id,
            );
            M('zy_detection')->add($d);
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'uid'=>$res['id'],
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'登录失败,账号或密码错误(Login failed,Account or password error)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //1.用户登录接口-通过RFID MAC登录
    public function zy_login_bynfc(){

        $rfid_mac= I('rfid');
        $rfid_mac = str_replace(":","-",$rfid_mac);

        $parame = array(
            'rfid'=>$rfid_mac,
        );
        AddLog($parame,'UserLoginByNFC');

        //查询用户名是否存在
        $w['rfid_mac']=$rfid_mac;

        $res = M('user')->where($w)->order('id desc')->find();
        if($res){
            $mid = $res['mid'];
            //用户登录成功，在检测表中写入用户检测状态
            $d = array(
                'uid'=>$res['id'],
                'equipment_id'=>$mid,
                'time'=>time()
            );
            M('zy_detection')->add($d);
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'uid'=>$res['id'],
                    'username'=>$res['name'],
                    'nickname'=>$res['nickname'],
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'登录失败,账号或密码错误(Login failed,Account not fund)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //通过机器ID检索机器上所有用户的信息
    public function zy_get_userlist_bymid(){

        $mid= I('mid');

        $parame = array(
            'mid'=>$mid,
        );
        AddLog($parame,'通过机器ID查询上面的所有用户');

        //查询用户名是否存在
        $w['mid']=$mid;

        $res = M('user')->where($w)->select();
        foreach ($res as $k=>$v){
            $res[$k]['password']=null;
            $res[$k]['num_total_tests']=$res[$k]['num_done_tests']+$res[$k]['num_available_tests'];
            $res[$k]['register_time']=date('Y-m-d H:i:s',$res[$k]['register_time']);
            if($res[$k]['org_id']==1){
                $res[$k]['org_name']='北京凤凰八音';
            }else if($res[$k]['org_id']==2){
                $res[$k]['org_name']='中益集团';
            }else if($res[$k]['org_id']==3){
                $res[$k]['org_name']='武汉橄榄无线';
            }
        }

        $this->ajaxReturn($res);
    }

    //用户注册接口
    public function zy_register(){
        $data = I('post.');
        AddLog($data,'用户注册');
        $register_name = I('register_name');
        $register_form = I('register_form');
        $register_type = I('register_type');
        $password      = I('password');
        $re_password   = I('re_password');
        $verify_code   = I('verify_code');
        $openid        = I('openid');
        $org_id=I('org_id');
        if(!$register_name || !$register_form || !$register_type || !$password){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $userinfo=array(
            'register_form'=>$register_form,
            'register_type'=>$register_type,
            'password'     =>$password,
            'register_time'=>time(),
            'user_form'    =>2,
            'openid'       =>$openid,
            'org_id'=> $org_id,
            'birthday'=> '1980-01-01'
        );
        if($register_type==1){
            $userinfo['name']=$register_name;
            //查询用户名是否已经被注册
            $w['name']=$userinfo['name'];
            $w['user_form']=2;
            $this->check_name_register($w);//验证用户名是否已经注册
        }elseif($register_type==2){
            $userinfo['phone']=$register_name;
            //这里验证手机号格式是否正确
            $this->check_phone($userinfo['phone']);
            //这里验证用户输入的手机验证码是否正确
            $this->check_verify($verify_code,$register_name,'phone');
        }elseif($register_type==3){
            //这里验证用户输入的邮箱验证码是否正确
            $userinfo['email']=$register_name;
            $this->check_email($userinfo['email']);
            //这里验证用户输入的邮箱验证码是否正确
            $this->check_verify($verify_code,$register_name,'email');
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'register_type参数错误'
                )
            );
            $this->ajaxReturn($arr);
        }
        //验证两次输入的密码是否相同
        $this->check_password($password,$re_password);

        $uid = M('user')->add($userinfo);
        if($uid){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'uid'=>$uid
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'注册失败'
            );
        }
        $this->ajaxReturn($arr);
    }

    //通过NFC注册用户
    //参数：rfid 注册的nfid(必填)
    //参数：password 注册密码(必填)
    //nickname 昵称
    //phone 电话
    //email 邮箱
    //birthday 生日(格式：1980-12-13)
    //sex 性别 (Man:1, Woman:2)
    //mid 机器ID (必填)
    public function zy_register_bynfc(){
        $data = I('post.');
        AddLog($data,'用户注册');
        $register_rfid=I('rfid');
        $password = I('password');
        $nickname = I('nickname');
        $phone=I('phone');
        $email=I('email');
        $birthday=I('birthday');
        $sex=I('sex');
        $mid=I('mid');
        $org_id=I('org_id');

        $register_name = $register_rfid;
        $register_form = 'NFC';
        $register_type = 4;//4代表NFC渠道注册

        if(!$mid ||!$register_name || !$register_form || !$register_type || !$password){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)',
                    'mid'=>$mid
                )
            );
            $this->ajaxReturn($arr);
        }
        $userinfo=array(
            'rfid_mac'=>$register_rfid,
            'register_form'=>$register_form,
            'register_type'=>$register_type,
            'password'     =>$password,
            'register_time'=>time(),
            'user_form'    =>2,//2代表中益用户
            'openid'       =>'',
            'org_id'=> $org_id,
            'birthday'=> '1980-01-01'
        );
        if($register_type==4){
            $userinfo['rfid_mac']=$register_name;
            $userinfo['name']=$nickname;

            $userinfo['nickname']=$nickname;
            $userinfo['phone']=$phone;
            $userinfo['email']=$email;
            $userinfo['birthday']=$birthday;
            $userinfo['sex']=$sex;
            $userinfo['mid']=$mid;

            //查询用户名是否已经被注册
            $w['name']=$userinfo['name'];
            $w['phone']=$userinfo['phone'];
            $w['email']=$userinfo['email'];

            $w['_logic'] = 'or';
            $map['_complex'] = $w;

            $this->check_name_register($map);//验证用户名是否已经注册
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'register_type参数错误'
                )
            );
            $this->ajaxReturn($arr);
        }
        if($register_name){
            $flag = M('user')->where('rfid_mac = "'.$register_name.'"')->select();
            print_r($flag);
            if($flag){
                $res = M('user')->where('rfid_mac = "'.$register_name.'"')->setField('rfid_mac', null);
            }
        }
        $uid = M('user')->add($userinfo);
        if($uid){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'Register Success',
                    'uid'=>$uid,
                    'userinfo'=>$userinfo,
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'Register Failed',
                'userinfo'=>$userinfo,
            );
        }
        $this->ajaxReturn($arr);
    }

    //用户手机获取验证码接口
    public function zy_phone_verify(){
        $phone = I('phone');
        //查询当前手机号今天已经发送了几条验证码
        $w_code = array(
            'login_name'=>$phone,
            'time' => array('between',array(strtotime(date('Y-m-d',time())),strtotime(date('Y-m-d',time()))+3600*24))
        );
        $count = M('verify_code')->where($w_code)->count();

        if($count>=5){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'今天发送验证码已经超过5次了'
                ),
            );
            $this->ajaxReturn($arr);
        }
        //先查询手机号是否已经注册
        $w['phone']=$phone;
        $w['user_form']=2;
        $this->check_phone_register($w);//验证手机号是否已经注册

        $res = $this->phone_verify($phone);
        if($res['code']==2){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    //'verify'=>$res['verify']
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'获取验证码失败（Failed to obtain verification code）',
                    //'verify'=>''
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //获取邮箱验证码接口
    public function zy_email_verify(){
        $email = I('email');
        //先查询邮箱是否已经注册
        $w['email']=$email;
        $w['user_form']=2;
        $this->check_email_register($w);//验证邮箱是否已经注册
        $res = $this->email_verify($email);
        if($res['code']==1){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    //'verify'=>$res['verify']
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'邮箱验证码发送失败（Failed to obtain verification code）',
                    //'verify'=>''
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //用户信息查询接口
    public function zy_userinfo(){
        $uid = I('uid');
        //判断用户id是否正确
        if(!$uid || !is_numeric($uid)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //判断数据库中是否有传入的id的用户
        $user = M('user')->where('id='.$uid)->find();
        if($user){
            //如果有直接输出数据
            $arr = array(
                'code'=>1,
                'ressult'=>array(
                    'msg'=>'success',
                    'userinfo'=>array(
                        'org_id'=>$user['org_id'],
                        'username'=>$user['name'],
                        'phone'   =>$user['phone'],
                        'email'  =>$user['email'],
                        'nickname'=>$user['nickname'],
                        'birthday'=>$user['birthday'],
                        'sex'     =>$user['sex'],
                        'head_pic'     =>$user['head_pic'],
                        'register_form'=>$user['register_form'],
                        'num_done_tests'=>$user['num_done_tests'],
                        'num_available_tests'=>$user['num_available_tests'],
                        'num_total_tests'=>$user['num_done_tests']+$user['num_available_tests']
                    )
                )
            );
        }else{
            //如果没有输出错误信息
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'没有找到用户信息(No user information found)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //修改用户信息接口
    public function zy_userinfo_update(){
        $sex = I('sex');
        $data = array(
            'id'      =>I('uid'),
            'birthday'=>I('birthday'),
            'nickname'=>I('nickname'),
            'sex'     =>I('sex')
        );
        $data = array_filter($data);
        //判断用户id是否正确
        if(!$data){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //判断用户sex传入是否正确
        if($sex && intval($sex) != 2 && intval($sex) != 1){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'sex参数错误,只能是1或2(sex Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'修改失败(Modify failed)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //修改手机号
    public function zy_update_phone(){
        $uid    = I('uid');
        $phone  = I('phone');
        $verify = I('code');
        //判断手机号是否正确
        $this->check_phone($phone);
        //判断验证码是否正确
        $this->check_verify($verify,$phone,'phone');
        $data = array(
            'id'=>$uid,
            'phone'=>$phone
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //修改邮箱
    public function zy_update_email(){
        $uid    = I('uid');
        $email  = I('email');
        $verify = I('code');
        //判断邮箱是否正确
        $this->check_email($email);
        //判断验证码是否正确
        $this->check_verify($verify,$email,'email');
        $data = array(
            'id'=>$uid,
            'email'=>$email
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //修改密码
    public function zy_update_password(){
        $uid    = I('uid');
        $password= I('password');
        $phone  = I('phone');
        $verify = I('code');
        //判断手机号是否正确
        $this->check_phone($phone);
        //判断验证码是否正确
        $this->check_verify($verify,$phone,'phone');
        $data = array(
            'id'=>$uid,
            'password'=>$password
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //轮询查询待检测用户接口
    public function zy_polling_query(){
        $mid = I('mid');
        $statue = 1;

        $res = M('zy_detection')->where('equipment_id ="'.$mid.'" and statue=0')->order('time desc')->find();
        if($res){
            $uid = $res['uid'];
            //查询用户信息
            $userinfo = M('user')->where('id='.$uid)->find();
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'username'=>$userinfo['name'],
                    'uid'=>$userinfo['id']
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'没有待检测用户(No user to be detected)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //上传微生物检测结果
    public function zy_upload_exam_data_micro(){
        $uid = I('uid');//用户id
        $exam_result=I('exam_result');//测试数据
        $exam_result=str_replace('&quot;','"',$exam_result);
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);

        $user = M('user')->where('id='.$uid)->find();
        $user['head_pic']=str_replace('http://cloud.musiccare.cn','C:\xampp\htdocs\nanhuyixiao\cloud_dev',$user['head_pic']);
        $user['head_pic']=str_replace('/','\\',$user['head_pic']);
        $info['examTime']=date("Y-m-d H:i:s");
        $info['userInfo']['portrait']=$user['head_pic'];
        $info['userInfo']['userId']=$user['id'];
        $info['userInfo']['userName']=$user['name'];
        $info['userInfo']['phone']=$user['phone'];
        $info['userInfo']['email']=$user['email'];
        $info['itemData']=$exam_result;
        $info=json_encode($info);
        $myfile = fopen("exam-result.json", "w") or die("Unable to open file!");
        fwrite($myfile, $info);
        fclose($myfile);
        $file_name=$user['name'].'_'.$user['phone'].'_'.$user['email'].'_'.date('YmdHis').'_'.$uid.'.pdf';
        exec('java -jar C:\xampp\htdocs\nanhuyixiao\cloud\ZhongYiPdfReport\pdfreport.jar -v -homeDir C:\xampp\htdocs\nanhuyixiao\cloud\ZhongYiPdfReport -func makeReport C:\xampp\htdocs\nanhuyixiao\cloud\exam-result.json C:\xampp\htdocs\nanhuyixiao\cloud\Uploads\Zy_Wx_pdf_report\\'.date('Y-m-d').'\\'.$file_name);
        $pdf_report_path=date('Y-m-d').'/'.$file_name;
        $data = array(
            'uid'=>$uid,
            'exam_result'=>$exam_result,
            'upload_time'=>time(),
            'type'=>1,
            'pdf_report_path'=>$pdf_report_path,
        );
        AddLog($data,'上传微生物检测结果');
        $res = M('zy_exam_result')->add($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //上传金属检测结果
    public function zy_upload_exam_data_heavy(){
        $uid = I('uid');//用户id
        $exam_result=I('exam_result');//测试数据
        $exam_result=str_replace('&quot;','"',$exam_result);
        // $exam_result=str_replace('\"','"',$exam_result);
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $user = M('user')->where('id='.$uid)->find();
        $user['head_pic']=str_replace('http://cloud.musiccare.cn','C:\xampp\htdocs\nanhuyixiao\cloud_dev',$user['head_pic']);
        $user['head_pic']=str_replace('/','\\',$user['head_pic']);
        $info['examTime']=date("Y-m-d H:i:s");
        $info['userInfo']['portrait']=$user['head_pic'];
        $info['userInfo']['userId']=$user['id'];
        $info['userInfo']['userName']=$user['name'];
        $info['userInfo']['phone']=$user['phone'];
        $info['userInfo']['email']=$user['email'];
        $info['itemData']=$exam_result;
        $info=json_encode($info);
        $myfile = fopen("exam-result.json", "w") or die("Unable to open file!");
        fwrite($myfile, $info);
        fclose($myfile);
        $file_name=$user['name'].'_'.$user['phone'].'_'.$user['email'].'_'.date('YmdHis').'_'.$uid.'.pdf';
        exec('java -jar C:\xampp\htdocs\nanhuyixiao\cloud\ZhongYiPdfReport\pdfreport.jar  -homeDir C:\xampp\htdocs\nanhuyixiao\cloud\ZhongYiPdfReport -func makeReport C:\xampp\htdocs\nanhuyixiao\cloud\exam-result.json C:\xampp\htdocs\nanhuyixiao\cloud\Uploads\Zy_Wx_pdf_report\\'.date('Y-m-d').'\\'.$file_name);
        $pdf_report_path=date('Y-m-d').'/'.$file_name;
        $data = array(
            'uid'=>$uid,
            'exam_result'=>$exam_result,
            'upload_time'=>time(),
            'type'=>2,
            'pdf_report_path'=>$pdf_report_path,
        );
        AddLog($data,'上传金属检测结果');
        $res = M('zy_exam_result')->add($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //上传金属检测结果
    public function zy_upload_report_json_data(){
        $this->zy_upload_exam_data_heavy();
    }

    //上传检测报告接口
    public function zy_upload_test_report(){
        $uid = I('uid');//用户id
        $_FILES['uid']=$uid;
        AddLog($_FILES,'上传检测报告');
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $file = $_FILES['file_name']['name'];
        $file = explode('.',$file);
        $count = count($file);
        $str = $file[$count-1];
        if($str != 'pdf'){
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'请先上传PDF文件'
                )
            );
            $this->ajaxReturn($res);
        }
        $upload = new \Think\Upload();// 实例化上传类
        $upload->exts = array('pdf');  //设置文件格式
        $upload->maxSize   =     10485760 ;// 设置附件上传大小10M
        $upload->savePath  =  '/ZY_data/'; // 设置附件上传目录
        $info   =   $upload->uploadOne($_FILES['file_name']);// 上传文件
        if (!$info) {
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'上传PDF文件失败'
                )
            );
            $this->ajaxReturn($res);
        }else{
            $data = array(
                'uid'=>$uid,
                'file_name'=>$info['name'],
                'upload_time'=>time(),
                'size'=>$info['size'],
                'md5'=>$info['md5'],
                'sha1'=>$info['sha1'],
                'url'=>'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads'.$info['savepath'].$info['savename']
            );
            $res = M('zy_exam_file')->add($data);
            if($res){
                $arr = array(
                    'code'=>1,
                    'result'=>array(
                        'msg'=>'success',
                        'info'=>$data
                    )
                );
            }
            $this->ajaxReturn($arr);
        }
    }
    //上传设备GPS信息接口
    public function zy_upload_gps_info(){
        $mid = I('mid');//设备id
        $gps_data = I('gps_data');//设备GPS信息
        if(!$mid || !$gps_data){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $data = array(
            'mid'=>$mid,
            'gps_data'=>$gps_data
        );
        //查询数据库中是否有设备id的信息
        $res = M('zy_equipment_gps')->where('mid="'.$mid.'"')->find();
        if($res){
           //如果有就更新
           $data['id']=$res['id'];
           $result = M('zy_equipment_gps')->save($data);
        }else{
            //没有就增加
            $result = M('zy_equipment_gps')->add($data);
        }
        if($result){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //上传检测设备信息接口
    public function zy_upload_equipment(){
        $mid = I('mid');
        $hardware_version = I('hardware_version');
        $firmware_version = I('firmware_version');
        $mac_software_version = I('mac_software_version');
        $ipad_software_version = I('ipad_software_version');
        $mac_serial_number= I('mac_serial_number');
        $mac_os_info = I('mac_os_info');
        $router_name_model = I('router_name_model');
        $router_firmware_version = I('router_firmware_version');
        $raspberry_name_model = I('raspberry_name_model');
        $raspberry_img_version = I('raspberry_img_version');
        $philips_bridge_firmware_version = I('philips_bridge_firmware_version');
        if(!$mid){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $data = array(
            'mid'=>$mid,
            'date'=>$date,
            'hardware_version'=>$hardware_version,
            'firmware_version'=>$firmware_version,
            'mac_software_version'=>$mac_software_version,
            'ipad_software_version'=>$ipad_software_version,
            'mac_serial_number'=>$mac_serial_number,
            'mac_os_info'=>$mac_os_info,
            'router_name_model'=>$router_name_model,
            'router_firmware_version'=>$router_firmware_version,
            'raspberry_name_model'=>$raspberry_name_model,
            'raspberry_img_version'=>$raspberry_img_version,
            'philips_bridge_firmware_version'=>$philips_bridge_firmware_version,
            'time'=>time()
        );
        //查询数据库中是否有设备id的信息
        $res = M('zy_equipment_info')->where('mid="'.$mid.'"')->find();
        if($res){
            //如果有就更新
            $data['id']=$res['id'];
            $result = M('zy_equipment_info')->save($data);
        }else{
            //没有就增加
            $result = M('zy_equipment_info')->add($data);
            echo "haha";
        }
        if($result){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //上传上传软件信息接口
    public function zy_upload_software(){
        $mid = I('mid');
        $version = I('version');
        $ipad_software_version= I('ipad_software_version');
        $os_info = I('os_info');
        if(!$mid){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $data = array(
            'mid'=>$mid,
            'version'=>$version,
            'ipad_software_version'=>$ipad_software_version,
            'os_info'=>$os_info
        );
        //查询数据库中是否有设备id的信息
        $res = M('zy_equipment_soft')->where('mid="'.$mid.'"')->find();
        if($res){
            //如果有就更新
            $data['id']=$res['id'];
            $result = M('zy_equipment_soft')->save($data);
        }else{
            //没有就增加
            $result = M('zy_equipment_soft')->add($data);
        }
        if($result){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //上传设备在线信息接口
    public function zy_upload_online_info(){
        $mid         = I('mid');
        $timestamp   = I('timestamp');
        $mac_addresss= I('mac_addresss');
        if(!$mid){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $data = array(
            'mid'=>$mid,
            'timestamp'=>$timestamp,
            'mac_addresss'=>$mac_addresss,
        );
        //查询数据库中是否有设备id的信息
        $res = M('zy_equipment_online')->where('mid="'.$mid.'"')->find();
        if($res){
            //如果有就更新
            $data['id']=$res['id'];
            $result = M('zy_equipment_online')->save($data);
        }else{
            //没有就增加
            $result = M('zy_equipment_online')->add($data);
        }
        if($result){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //上传用户指纹图片接口
    public function zy_upload_fingerprint(){
        $uid = I('uid');//用户id
        $_FILES['uid']=$uid;
        AddLog($_FILES,'上传用户指纹图片');
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $file = $_FILES['finger_pic']['name'];
        $file = explode('.',$file);
        $count = count($file);
        $str = $file[$count-1];

        if($str != 'gif' && $str !='png' && $str != 'jpeg' && $str != 'jpg'){
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'请上传gif、png、jpeg或jpg格式图片'
                )
            );
            $this->ajaxReturn($res);
        }
        $upload = new \Think\Upload();// 实例化上传类
        $upload->exts = array('gif','png','jpg','jpeg');  //设置文件格式
        $upload->maxSize   =     10485760 ;// 设置附件上传大小10M
        $upload->savePath  =  '/Fingerprint_IMG/'; // 设置附件上传目录
        $info   =   $upload->uploadOne($_FILES['finger_pic']);// 上传文件
        if (!$info) {
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'上传图片失败'
                )
            );
            $this->ajaxReturn($res);
        }else{
            $data = array(
                'uid'=>$uid,
                'file_name'=>$info['name'],
                'upload_time'=>time(),
                'size'=>$info['size'],
                'md5'=>$info['md5'],
                'sha1'=>$info['sha1'],
                'url'=>'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads'.$info['savepath'].$info['savename']
            );
            $res = M('zy_fingerprint_img')->add($data);
            if($res){
                $arr = array(
                    'code'=>1,
                    'result'=>array(
                        'msg'=>'success',
                        'info'=>$data
                    )
                );
            }
            $this->ajaxReturn($arr);
        }
    }

    //上传检测报告PDF文件
    public function zy_upload_pdf(){
        $uid = I('uid');//用户id
        $_FILES['uid']=$uid;
        AddLog($_FILES,'上传检测报告');
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $userInfo= M('user')->where('id='.$uid)->find();
        $file = $_FILES['file_name']['name'];
        $file = explode('.',$file);
        $count = count($file);
        $str = $file[$count-1];
        $str = strtolower($str);
        if($str != 'pdf'){
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'Please upload *.pdf file.',
                    'info'=>$file
                )
            );
            $this->ajaxReturn($res);
        }
        $upload = new \Think\Upload();// 实例化上传类
        $upload->exts = array('pdf');  //设置文件格式
        $upload->maxSize   =     1048576000 ;// 设置附件上传大小10M
        //$upload->savePath  =  '/ZY_data/'; // 设置附件上传目录
        //$info   =   $upload->uploadOne($_FILES['file_name']);// 上传文件
        $upload->savePath  =  '/ZY_data/'; // 设置附件上传目录
        $str = iconv('UTF-8', 'GBK//IGNORE', $userInfo['name']);
        $returnName = sprintf('%s_%s_%s_%s_%06d', $userInfo['name'],$userInfo['phone'],$userInfo['email'],date('YmdHis'), $uid);
        $upload->saveName = sprintf('%s_%s_%s_%s_%06d', $str,$userInfo['phone'],$userInfo['email'],date('YmdHis'), $uid);
        $info = $upload->uploadOne($_FILES['file_name']);

        if (!$info) {
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed to upload pdf file',
                    'info'=>$upload->getError()
                )
            );
            $this->ajaxReturn($res);
        }else{
            $data = array(
                'uid'=>$uid,
                'file_name'=>$info['name'],
                'upload_time'=>time(),
                'time_str'=>date("Y-m-d h:i:sa"),
                'size'=>$info['size'],
                'md5'=>$info['md5'],
                'sha1'=>$info['sha1'],
                'url'=>'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads'.$info['savepath'].$returnName.".pdf"
            );
            $res = M('zy_exam_file')->add($data);
            if($res){
                $arr = array(
                    'code'=>1,
                    'result'=>array(
                        'msg'=>'success',
                        'info'=>$data
                    )
                );
            }
            $this->ajaxReturn($arr);
        }
    }

    //更新用户头像信息
    public function zy_update_head_pic(){
        $data = array(I('post.'),$_FILES['head_pic']);
        AddLog($data,'修改用户头像接口zy_update_head_pic');
        $file = $_FILES['head_pic']['name'];
        if($file){
            $file = explode('.',$file);
            $count = count($file);
            $str = $file[$count-1];
            if($str != 'gif' && $str !='png' && $str != 'jpeg' && $str != 'jpg'){
                $res = array(
                    'code'=>0,
                    'result'=>array(
                        'msg'=>'请上传gif、png、jpeg或jpg格式图片'
                    )
                );
                $this->ajaxReturn($res);
            }
            $upload = new \Think\Upload();// 实例化上传类
            $upload->exts = array('gif','png','jpg','jpeg');  //设置文件格式
            $upload->maxSize   =     5485760 ;// 设置附件上传大小5M
            $upload->savePath  =  '/User_head_IMG/'; // 设置附件上传目录
            $info   =   $upload->uploadOne($_FILES['head_pic']);// 上传文件
            if(!$info){
                $arr = array(
                    'code'=>0,
                    'result'=>array(
                        'msg'=>'用户头像上传失败',
                        'info'=>$upload->getError()
                    )
                );
                $this->ajaxReturn($arr);
            }
            $head_pic='http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads'.$info['savepath'].$info['savename'];
        }

        $data = array(
            'id'      =>I('uid'),
            'head_pic'=>$head_pic
        );
        $data = array_filter($data);
        //判断用户id是否正确
        if(!$data){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }

        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'head_pic'=>$head_pic,
                    'data'=>$data
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'修改失败(Modify User Head Image failed)',
                    'data'=>$data
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    /**
     * 上传检测机器状态信息
     * 参数：
     * state_emergency_switch	紧急开关
     * state_ear_light	指示灯
     * state_door	舱门状态
     * state_lifting	脚台状态
     * state_weight	体重检测状态
     * state_massage_chair	按摩椅脚台状态
     * 以上参数均为 int 型，值由德国专家定义。默认状态值全部为0
     * 其中 state_ear_light 代表整机状态，值包括“使用中”、“闲置”等，由德方定义。
     * 服务端在处理用户扫码登录时，仅“闲置”状态的机器允许用户登录，其他状态下用户登录操作不成功。
     *
     **/
    public function report_machine_states(){
        $mid = I('mid');

        $state_emergency_switch = I('state_emergency_switch',0);
        $state_ear_light = I('state_ear_light',0);
        $state_door = I('state_door',0);
        $state_lifting = I('state_lifting',0);
        $state_weight = I('state_weight',0);
        $state_tesla_left = I('state_tesla_left',0);
        $state_tesla_right = I('state_tesla_right',0);

        $data = array(
            'serial_number' => I('mid'),
            'state_emergency_switch'      =>I('state_emergency_switch'),
            'state_ear_light'=>I('state_ear_light'),
            'state_door'=>I('state_door'),
            'state_lifting'     =>I('state_lifting'),
            'state_weight'     =>I('state_weight'),
            'state_tesla_left'     =>I('state_tesla_left'),
            'state_tesla_right'     =>I('state_tesla_right'),
            'last_state_time'=>date("Y-m-d H:i:s"),
        );


        //$data = array_filter($data);
        //判断用户id是否正确
        if(!$mid){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数mid为空(Parameter mid is null)',
                    'data'=>$data
                )
            );
            $this->ajaxReturn($arr);
        }

        $equipmentRes = M('qrcode_equipment')->where('serial_number="'.$mid.'"')->find();
        if(!$equipmentRes){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'没有对应MID的检测仪(Machine not found of this mid value)',
                    'data'=>$data
                )
            );
            $this->ajaxReturn($arr);
        }

        //1判断用户state_emergency_switch传入是否正确
        if(!is_string($state_emergency_switch)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_emergency_switch参数错误,需要String类型(state_emergency_switch parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //2判断用户state_ear_light传入是否正确
        if(!is_string($state_ear_light)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_ear_light参数错误,需要String类型(state_ear_light parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //3判断用户state_door传入是否正确
        if(!is_string($state_door)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_door参数错误,需要String类型(state_door parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //4判断用户state_lifting传入是否正确
        if(!is_string($state_lifting)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_lifting参数错误,需要String类型(state_lifting parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //5判断用户state_weight传入是否正确
        if(!is_string($state_weight)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_weight参数错误,需要String类型(state_weight parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }
        //6判断用户state_massage_chair传入是否正确
        // if(!is_numeric($state_massage_chair)){
        //     $arr = array(
        //         'code'=>0,
        //         'result'=>array(
        //             'msg'=>'state_massage_chair参数错误,需要int类型(state_massage_chair parameter error, must be int var)'
        //         )
        //     );
        //     $this->ajaxReturn($arr);
        // }

        //7判断用户state_tesla_left传入是否正确
        if(!is_string($state_tesla_left)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_tesla_left,需要String类型(state_tesla_left parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }

        //8判断用户state_tesla_right传入是否正确
        if(!is_string($state_tesla_right)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'state_tesla_right,需要String类型(state_tesla_right parameter error, must be int var)'
                )
            );
            $this->ajaxReturn($arr);
        }

        $where['serial_number']=$mid;
        $modelEquipment=M('qrcode_equipment');
        $res = $modelEquipment->where($where)->save($data);
        if($res !== false){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'Update Machine States Success.',
                    'data'=>$data,
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'修改失败(Modify failed)',
                    'data'=>$data,
                    'info'=>$modelEquipment->getError(),
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //获取用户的检测报告的下载地址
    public function get_user_reportfile(){
        $uid=I('uid');
        $map['uid']=$uid;
        $res = M('zy_exam_file')->order('id desc')->where($map)->find();

        if($res){
            $res['upload_time'] = date('Y-m-d H:i:s', $res['upload_time']);
            $res['size'] = number_format($res['size']/(1024*1024),2) . "MB";
            $arr = array(
                'code'=>1,
                'report'=>$res
            );
        } else {
            $arr = array(
                'code'=>0,
                'report'=>'没有查询到该用户检测报告（Report Files not found.）'
            );
        }


        $this->ajaxReturn($arr);
    }

    //获取检测仪的二维码以及其他信息
    //传入参数：mid 机器ID编码
    public function get_machine_qrcode(){
        $mid=I('mid');
        $map['serial_number']=$mid;
        $res = M('qrcode_equipment')->where($map)->order('id desc')->find();
        AddLog($res,'get_machine_qrcode');

        if($res){
            $data['id']=$res['id'];
            $data['qrcode_url']=$res['qrcode_url'];
            $data['mid']=$res['serial_number'];
            $data['equipment_model']=$res['equipment_model'];

            $arr = array(
                'code'=>1,
                'report'=>$data
            );
        } else {
            $arr = array(
                'code'=>0,
                'report'=>'没有查询到该mid机器的二维码（QRCode info not found.）'
            );
        }


        $this->ajaxReturn($arr);
    }

    //查询所有的检测报告信息
    public function get_all_reports(){

        $res = M('zy_exam_file')->order('id desc')->limit(10)->select();
        foreach($res as $k =>$v){
            $res[$k]['upload_time'] = date('Y-m-d H:i:s', $v['upload_time']);
            $res[$k]['size'] = number_format($v['size']/(1024*1024),2) . "MB";
        }

        $this->ajaxReturn($res);
    }

    //查询所有的检测报告上传日志
    public function get_report_logs(){
        $map['msg'] = array('like','%上传检测报告%');
        $res = M('log')->order('id desc')->limit(20)->where($map)->select();


        header('Content-Type:application/json; charset=utf-8');
        $res=   json_encode($res);
        $res1 = preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $res);
        exit($res1);
    }

    public function test_redis(){
        //登录成功后向Redis写入当前检测的用户和检测仪的信息
        \Predis\Autoloader::register();
        $client = new \Predis\Client([
            'scheme' => 'tcp',
            'host'   => '127.0.0.1',
            'port'   => 6379,
        ]);
        $auth = $client->auth('musiccare'); //设置密码
        //var_dump($auth);

        $client->set('cfg','<br>redis缓存设置了');
        echo $client->get('cfg');


    }

    //根据机构id查询该机构下所有检测仪
    public function get_all_equipment(){
        $org_id = I('org_id');
        $res = M('qrcode_equipment')->where('org_id = "'.$org_id.'"')->select();
        foreach ($res as $key=>$val){
            $res[$key]['date_of_production']=date('Y-m-d H:i:s',$res[$key]['date_of_production']);
            $res[$key]['create_time']=date('Y-m-d H:i:s',$res[$key]['create_time']);
        }
        //判断机构id是否正确
        if(!$org_id){
            $arr = array(
                'code'=>0,
                'msg'=>'参数org_id为空(Parameter org_id is null)',
                'data'=>$res
            );
            $this->ajaxReturn($arr);
        }

        if($res){
            $arr = array(
                'code'=>1,
                'msg'=>'success',
                'data' => $res
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'fail'
            );
        }
        $this->ajaxReturn($arr);
    }

    //检测机器是否被占用接口
    public function get_machine_using_uid(){
        $mid = I('mid');
        $res = M('qrcode_equipment')->field('using_uid')->where('serial_number = "'.$mid.'"')->select();
        if($res[0]['using_uid']){
            $arr = array(
                'code'=>1,
                'msg'=>'机器被占用',
                'uid' => $res[0]['using_uid']
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'机器空闲',
                'uid'=>0
            );
        }
        $this->ajaxReturn($arr);
    }

    //设置机器被占用的uid
    public function set_machine_using_uid(){
        $mid = I('mid');
        $uid = I('uid');
        $res = M('qrcode_equipment')->where('serial_number = "'.$mid.'"')->setField('using_uid', $uid);
        if($uid){
            $arr = array(
                'code'=>1,
                'msg'=>'机器被占用',
                'uid' => $uid
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'机器空闲',
                'uid'=>0
            );
        }
        $this->ajaxReturn($arr);
    }

    //根据机构id查询该机构下所有用户
    public function get_all_users_of_org(){
        $org_id = I('org_id');
        $res = M('user')->where('org_id = "'.$org_id.'"')->select();
        foreach ($res as $key=>$val){
            $res[$key]['register_time']=date('Y-m-d H:i:s',$res[$key]['register_time']);
            if($res[$key]['org_id']==1){
                $res[$key]['org_name']='北京凤凰八音';
            }else if($res[$key]['org_id']==2){
                $res[$key]['org_name']='中益集团';
            }else if($res[$key]['org_id']==3){
                $res[$key]['org_name']='武汉橄榄无线';
            }
        }
        //判断机构id是否正确
        if(!$org_id){
            $arr = array(
                'code'=>0,
                'msg'=>'参数org_id为空(Parameter org_id is null)',
                'data'=>$res
            );
            $this->ajaxReturn($arr);
        }

        if($res){
            $arr = array(
                'code'=>1,
                'msg'=>'success',
                'data' => $res
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'fail'
            );
        }
        $this->ajaxReturn($arr);
    }

    //获取系统名称
    public function get_sys_configs(){
      $config = M('sys_configs')->where('id = 1')->field('id',true)->find();
      $this->ajaxReturn($config);
    }

    //下载检测报告
    public function download_jcbg($uid,$upload_time){
      //$uid = I('get.uid');
      $jcbg = M('zy_exam_result')->where('uid='.$uid. ' and ' .'upload_time='.$upload_time)->find();
      $time = date('Y-m-d',$upload_time);
      header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename=$time-$uid-json.csv");

      $jcbg = json_decode($jcbg['exam_result'],true);


      foreach($jcbg as $key=>$value) {
        switch($value){
            case $value>=0 && $value<95:
                 $risk = "低风险";
                 break;
            case $value>=95 && $value<=99:
                 $risk = "中风险";
                 break;
            case $value==100:
                 $risk = "高风险";
        }
        $num_zh=M('zy_num_zh');
        $titel = $num_zh->where('Given_Number="'.$key.'"')->field('CN_Titel')->find();
        // $sql = $num_zh->getLastSql();
        // echo $sql;
        $titel = $titel['cn_titel'];
        $titel =iconv('utf-8','gb2312',$titel);
        $risk =iconv('utf-8','gb2312',$risk);
        echo $key.','.$titel.','.$risk.','.$value."\n";
      }
    }

    //音乐片段计算
    public function brainwave_alpha_gama_ratio_max(){
        $uid = I('get.uid');
        $num = I('get.num');
        if(!$uid){
            $arr = array(
                'code'=>0,
                'msg'=>'参数不正确'
            );
            $this->ajaxReturn($arr);
        }
        if($num!=null){
            $condition['uid'] = $uid;
            $condition['num'] = $num;
            $condition['instrument'] = "";
            $condition['scene'] = array(array('neq','m001'),array('neq','m002'),array('neq','m003'),array('neq','m004'),array('neq','m005'),array('neq','m006'),array('neq','m007'),array('neq','m008'),'and'); 
            $condition['_logic'] = 'AND';
            $res = M('exam_music_result_copy')->where($condition)->select();
        }else{
            $condition['uid'] = $uid;
            $condition['instrument'] = "";
            $condition['scene'] = array(array('neq','m001'),array('neq','m002'),array('neq','m003'),array('neq','m004'),array('neq','m005'),array('neq','m006'),array('neq','m007'),array('neq','m008'),'and'); 
            $condition['_logic'] = 'AND';
            $num = M('exam_music_result_copy')->where('uid='.$uid)->max('num');
            $condition['num'] = $num;
            $res = M('exam_music_result_copy')->where($condition)->select();
        }


        
        //echo M('exam_music_result_copy')->getLastSql();
        foreach ($res as $key=>$val){
                $lowalpha = 0;
                $highalpha = 0;
                $lowgamma = 0;
                $highgamma = 0;
                /****/
                $arr_highalpha = explode(',',$val['highalpha']);
                foreach ($arr_highalpha as $val1){
                    $highalpha += $val1;
                }
                /****/
                $arr_lowgamma = explode(',',$val['lowgamma']);
                foreach ($arr_lowgamma as $val1){
                    $lowgamma += $val1;
                }
                /****/
                $arr_highgamma = explode(',',$val['highgamma']);
                foreach ($arr_highgamma as $val1){
                    $highgamma += $val1;
                }
                
                $arr_lowalpha = explode(',',$val['lowalpha']);
                foreach ($arr_lowalpha as $val1){
                    $lowalpha += $val1;
                }
                //$all_eeg=$highalpha+$lowgamma+$highgamma+$lowalpha;
                $res[$key]['xn']=($highalpha+$lowalpha)/($lowgamma+$highgamma);
            }
        $xn = array();
        foreach($res as $val){
            $xn[]=$val["xn"];
        }
        array_multisort($xn, SORT_DESC, $res);
        $new=array();
        foreach($res as $k=>$v){
                $m = $res[$k]['scene'];
                $x = (float)sprintf("%.2f", $res[$k]['xn']);
                $new[$k]=[$m,$x];
        }
        $this->ajaxReturn($new);
    }

    public function brainwave_delta_theta_sum_max(){
        $uid = I('get.uid');
        $num = I('get.num');
        if(!$uid){
            $arr = array(
                'code'=>0,
                'msg'=>'参数不正确'
            );
            $this->ajaxReturn($arr);
        }
        if($num!=null){
            $condition['uid'] = $uid;
            $condition['num'] = $num;
            $condition['instrument'] = "";
            $condition['scene'] = array(array('neq','m001'),array('neq','m002'),array('neq','m003'),array('neq','m004'),array('neq','m005'),array('neq','m006'),array('neq','m007'),array('neq','m008'),'and'); 
            $condition['_logic'] = 'AND';
            $res = M('exam_music_result_copy')->where($condition)->select();
        }else{
            $condition['uid'] = $uid;
            $condition['instrument'] = "";
            $condition['scene'] = array(array('neq','m001'),array('neq','m002'),array('neq','m003'),array('neq','m004'),array('neq','m005'),array('neq','m006'),array('neq','m007'),array('neq','m008'),'and'); 
            $condition['_logic'] = 'AND';
            $num = M('exam_music_result_copy')->where('uid='.$uid)->max('num');
            $condition['num'] = $num;
            $res = M('exam_music_result_copy')->where($condition)->select();
        }
        
        //echo M('exam_music_result_copy')->getLastSql();
        foreach ($res as $key=>$val){
                $theta = 0;
                $lowalpha = 0;
                $highalpha = 0;
                $lowbeta = 0;
                $hightbeta = 0;
                $lowgamma = 0;
                $highgamma = 0;
                $detal = 0;
                $arr_theta = explode(',',$val['theta']);
                foreach ($arr_theta as $val1){
                    $theta += $val1;
                }
                /****/
                $arr_highalpha = explode(',',$val['highalpha']);
                foreach ($arr_highalpha as $val1){
                    $highalpha += $val1;
                }
                /****/
                $arr_lowbeta = explode(',',$val['lowbeta']);
                foreach ($arr_lowbeta as $val1){
                    $lowbeta += $val1;
                }
                /****/
                $arr_hightbeta = explode(',',$val['hightbeta']);
                foreach ($arr_hightbeta as $val1){
                    $hightbeta += $val1;
                }
                /****/
                $arr_lowgamma = explode(',',$val['lowgamma']);
                foreach ($arr_lowgamma as $val1){
                    $lowgamma += $val1;
                }
                /****/
                $arr_highgamma = explode(',',$val['highgamma']);
                foreach ($arr_highgamma as $val1){
                    $highgamma += $val1;
                }
                /****/
                $arr_detal = explode(',',$val['delta']);
                foreach ($arr_detal as $val1){
                    $detal += $val1;
                }
                
                $arr_lowalpha = explode(',',$val['lowalpha']);
                foreach ($arr_lowalpha as $val1){
                    $lowalpha += $val1;
                }
                $all_eeg=$theta+$highalpha+$lowbeta+$hightbeta+$lowgamma+$highgamma+$detal+$lowalpha;
                $res[$key]['xn']=($theta/$all_eeg)+($detal/$all_eeg);
            }
        $xn = array();
        foreach($res as $val){
            $xn[]=$val["xn"];
        }
        array_multisort($xn, SORT_DESC, $res);
        $new=array();
        foreach($res as $k=>$v){
                $m = $res[$k]['scene'];
                $x = (float)sprintf("%.4f", $res[$k]['xn']);
                $new[$k]=[$m,$x];
        }
        $this->ajaxReturn($new);
    }

    //获取脑波报告的最后上传时间
    public function get_nbbg_lastest_time(){
        $uid = I('uid');
        $res = M('exam_result_copy')->field('uid,num,max(time)')->where('uid='.$uid)->group('num')->select();
        foreach($res as &$val){
            $val['time']=$val['max(time)'];
        }
        $this->ajaxReturn($res);
    }

    //查看连续脑波报告
    public function get_user_nbbg(){
        $uid = I('uid');
        $time = I('time');
        $arr = M('exam_result_copy')->where('uid='.$uid. ' and'.' time='.$time)->find();
        $num = $arr['num'];
        if(!$uid){
            $arr = array(
                'code'=>0,
                'msg'=>'参数不正确'
            );
            $this->ajaxReturn($arr);
        }
        $w = array(
            'uid'=>$uid,
            'num'=>$num
        );
        $res = M('exam_result_copy')->where($w)->select();
        
        $data = array();
        foreach ($res as $val){
            $data['id'] =$val['id'];
            $data['uid'] =$val['uid'];
            $data['num'] =$val['num'];
            $data['time'] =$val['time'];
            $data['hightbeta'] .= $val['hightbeta'].',';
            $data['lowbeta'] .= $val['lowbeta'].',';
            $data['lowgamma'] .=$val['lowgamma'].',';
            $data['theta'] .=$val['theta'].',';
            $data['attention'] .=$val['attention'].',';
            $data['lowalpha'] .=$val['lowalpha'].',';
            $data['highalpha'] .=$val['highalpha'].',';
            $data['delta'] .=$val['delta'].',';
            $data['singel'] .=$val['singel'].',';
            $data['meditation'] .=$val['meditation'].',';
            $data['highgamma'] .=$val['highgamma'].',';
        }
        $theta = 0;
        $lowalpha = 0;
        $highalpha = 0;
        $lowbeta = 0;
        $hightbeta = 0;
        $lowgamma = 0;
        $highgamma = 0;
        $arr_theta = explode(',',rtrim($data['theta'],','));
        foreach ($arr_theta as $val1){
            $theta += $val1;
        }
        $index = array_search(max($arr_theta), $arr_theta);
        $max_theta = $arr_theta[$index];
        $arr_lowalpha = explode(',',rtrim($data['lowalpha'],','));
        /****/
        foreach ($arr_lowalpha as $val1){
            $lowalpha += $val1;
        }
        $index = array_search(max($arr_lowalpha), $arr_lowalpha);
        $max_lowalpha = $arr_lowalpha[$index];
        /****/
        $arr_highalpha = explode(',',rtrim($data['highalpha'],','));
        foreach ($arr_highalpha as $val1){
            $highalpha += $val1;
        }
        $index = array_search(max($arr_highalpha), $arr_highalpha);
        $max_highalpha = $arr_highalpha[$index];
        /****/
        $arr_lowbeta = explode(',',rtrim($data['lowbeta'],','));
        foreach ($arr_lowbeta as $val1){
            $lowbeta += $val1;
        }
        $index = array_search(max($arr_lowbeta), $arr_lowbeta);
        $max_lowbeta = $arr_lowbeta[$index];
        /****/
        $arr_hightbeta = explode(',',rtrim($data['hightbeta'],','));
        foreach ($arr_hightbeta as $val1){
            $hightbeta += $val1;
        }
        $index = array_search(max($arr_hightbeta), $arr_hightbeta);
        $max_hightbeta = $arr_hightbeta[$index];
        /****/
        $arr_lowgamma = explode(',',rtrim($data['lowgamma'],','));
        
        foreach ($arr_lowgamma as $val1){
            $lowgamma += $val1;
        }
        $index = array_search(max($arr_lowgamma), $arr_lowgamma);
        $max_lowgamma = $arr_lowgamma[$index];
        /****/
        $arr_highgamma = explode(',',rtrim($data['highgamma'],','));
        foreach ($arr_highgamma as $val1){
            $highgamma += $val1;
        }
        $index = array_search(max($arr_highgamma), $arr_highgamma);
        $max_highgamma = $arr_highgamma[$index];
        /****/
        $all=$theta+$lowalpha+$highalpha+$lowbeta+$hightbeta+$lowgamma+$highgamma;
        $res1[0]['title']=L('_EEG_VALUE_REPORT');
        $content=array(
            L('WAVE_THETA') => (sprintf("%.4f", $theta/$all)*100).'%',
            L('WAVE_LOWALPHAL') => (sprintf("%.4f",$lowalpha/$all)*100).'%',
            L('WAVE_HIGHALPHA') => (sprintf("%.4f",$highalpha/$all)*100).'%',
            L('WAVE_LOWBETA') => (sprintf("%.4f",$lowbeta/$all)*100).'%',
            L('WAVE_HEIGHTBETA') => (sprintf("%.4f",$hightbeta/$all)*100).'%',
            L('WAVE_LOWGAMMA') => (sprintf("%.4f",$lowgamma/$all)*100).'%',
            L('WAVE_HEIGHTGAMMA') => (sprintf("%.4f",$highgamma/$all)*100).'%',
        );
        $res1[1]['title']=L('_EEG_PEAKVALUE_REPORT');
        $content_v = array(
                L('WAVE_THETA') => $max_theta,
                L('WAVE_LOWALPHAL') => $max_lowalpha,
                L('WAVE_HIGHALPHA') => $max_highalpha,
                L('WAVE_LOWBETA') => $max_lowbeta,
                L('WAVE_HEIGHTBETA') => $max_hightbeta,
                L('WAVE_LOWGAMMA') => $max_lowgamma,
                L('WAVE_HEIGHTGAMMA') => $max_highgamma,
        );
        $arr_meditation = explode(',',rtrim($data['meditation'],','));
        $index = array_search(max($arr_meditation), $arr_meditation);
        $max_meditation = $arr_meditation[$index];
        $arr_Attention = explode(',',rtrim($data['attention'],','));
        $index = array_search(max($arr_Attention), $arr_Attention);
        $max_attention = $arr_Attention[$index];
    
        $res1[0]['content']=$content;
        $res1[1]['content']=$content_v;
    
        $res1[4]['title']=L('_M_A_PEAKVALUE_REPORT');
        $content_m = array(
            L('WAVE_MEDITATION')=>$max_meditation,
            L('WAVE_ATTENTION')=>$max_attention,
        );
        $res1[4]['content']=$content_m;
        //冥想次数
        $num_meditation = count($arr_meditation);
        //关注次数
        $num_attention  = count($arr_Attention);
        $meditation_m = 0;
        $attention_m =0;
        foreach ($arr_meditation as $key_n=>$val_n){
            if($val_n>$arr_Attention[$key_n]){
                $num_meditation ++;
                $meditation_m += $val_n-$arr_Attention[$key_n];
            }
            if($val_n<$arr_Attention[$key_n]){
                $num_attention ++;
                $attention_m += $arr_Attention[$key_n]-$val_n;
            }
        }
        $num_meditation_res = sprintf("%.2f",$num_meditation/($num_meditation+$num_attention));
        $num_attention_res  = sprintf("%.2f",$num_attention/($num_meditation+$num_attention));
        $attention_m_res  = sprintf("%.2f",$attention_m/($meditation_m+$attention_m));
        $meditation_m_res = sprintf("%.2f",$meditation_m/($meditation_m+$attention_m));
        $res1[3]['title']=L('_M_A_VALUE_REPORT');
        $content_n = array(
            array(
                'name'=>L('_NUM_VALUE'),
                'data'=>array(
                    L('WAVE_MEDITATION')=>($meditation_m_res*100).'%',
                    L('WAVE_ATTENTION')=>($attention_m_res*100).'%',
                ),
            ),
            array(
                'name'=>L('_NUM_VALUE'),
                'data'=>array(
                    L('WAVE_MEDITATION')=>($num_meditation_res*100).'%', 
                    L('WAVE_ATTENTION')=>($num_attention_res*100).'%', 
                )
            )
        );
    
        $res1[3]['content']=$content_n;
        
        $this->ajaxReturn($res1);
    }

    //用户搜索接口
    public function user_search(){
        $key_word = I('get.key_word');
        if($key_word){
            $word='%'.$key_word.'%';
            $condition['_string']= 'id like "' 
                                    .$word
                                    .'" OR  name  like  "'
                                    .$word  
                                    .'" OR  nickname  like "'
                                    .$word
                                    .'" OR  phone  like "'
                                    .$word
                                    .'" OR  email  like "'
                                    .$word
                                    .'"';
            $list = M('user')->where($condition)->order('register_time desc')->select();
            $this->ajaxReturn($list);
        }
    }

    //微信用户编辑个人信息接口
    public function user_info_edit(){
        if(IS_POST){
            $id =I('id');
            $name= I('name');
            $nickname=I('nickname');
            $phone=I('phone');
            $email = I('email');
            $sex = I('sex');
            $birthday = I('birthday');
            $data = array(
                'id'=>$id,
                'name'  =>$name,
                'nickname'=>$nickname,
                'phone'=>$phone,
                'email'=>$email,
                'sex'=>$sex,
                'birthday'=>$birthday,
            );
            $res = M('user')->where('id='.$id)->save($data);
            if($res){
                $arr = array(
                    'code'=>1,
                    'msg'=>L('_SUCCESS')
                );
            }else{
                $arr = array(
                    'code'=>0,
                    'msg'=>L('_FAIL')
                );
            }
            $this->ajaxReturn($arr);
        }
    }

}
